package info.batcloud.fanli.core.service.impl;

import info.batcloud.fanli.core.constants.CacheNameConstants;
import info.batcloud.fanli.core.dto.ChannelDTO;
import info.batcloud.fanli.core.entity.Channel;
import info.batcloud.fanli.core.repository.ChannelRepository;
import info.batcloud.fanli.core.service.ChannelService;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@CacheConfig(cacheNames = CacheNameConstants.CHANNEL)
public class ChannelServiceImpl implements ChannelService {

    @Inject
    private ChannelRepository channelRepository;

    @Override
    public List<ChannelDTO> findAll() {
        return of(channelRepository.findAllByDeleted(false));
    }

    @Override
    @Cacheable(key = "#id")
    public ChannelDTO findById(long id) {
        Channel channel = channelRepository.findOne(id);
        if (channel == null) {
            return null;
        }
        ChannelDTO dto = new ChannelDTO();
        BeanUtils.copyProperties(channel, dto);
        return dto;
    }

    @Override
    public ChannelDTO addChannel(String name) {
        Channel channel = new Channel();
        channel.setName(name);
        channel.setCreateTime(new Date());
        channelRepository.save(channel);
        return of(channel);
    }

    @Override
    @CacheEvict(key = "#id+''")
    public void updateChannel(long id, String name) {
        Channel channel = channelRepository.findOne(id);
        channel.setName(name);
        channelRepository.save(channel);
    }

    @Override
    @CacheEvict(key = "#id+''")
    public void deleteById(long id) {
        Channel channel = channelRepository.findOne(id);
        channel.setDeleted(true);
        channelRepository.save(channel);
    }

    private List<ChannelDTO> of(List<Channel> channelList) {
        return channelList.stream().map(c -> of(c)).collect(Collectors.toList());
    }

    private ChannelDTO of(Channel channel) {
        ChannelDTO dto = new ChannelDTO();
        BeanUtils.copyProperties(channel, dto);
        return dto;
    }
}
